package org.mapki;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.TextView;

public class DescriptionActivity extends Activity {
	private ImageAdapter imgAdapter;
	private OnClickListener openMapListener;
	private final static String IMG_DIR = "img";
	private final static String GPX_DIR = "gpx";
	private final static String TXT_DIR = "txt";
	private String routeDirectoryPath;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_desc);
		imgAdapter = new ImageAdapter(getBaseContext());
		TextView txt = (TextView) findViewById(R.id.TrasaDescription);
		routeDirectoryPath = (String) getIntent().getSerializableExtra(
				"route_dir");
		String description = loadDescription(routeDirectoryPath);
		txt.setText(description);
		Bitmap[] images = loadImages(routeDirectoryPath);
		imgAdapter.setImages(images);
		//View view = (View)findViewById(R.id.RelLayout);
		imgAdapter.setSize(200,200);
		
		Gallery g = (Gallery) findViewById(R.id.gallery);
		g.setAdapter(imgAdapter);
		/*
		 * g.setOnItemClickListener(new OnItemClickListener() { public void
		 * onItemClick(AdapterView parent, View v, int position, long id) {
		 * Toast.makeText(DescriptionActivity.this, "" + position,
		 * Toast.LENGTH_SHORT).show(); } });
		 */
		openMapListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				openMap();
			}
		};
		Button openMapBtn = (Button) findViewById(R.id.openMapButton);
		openMapBtn.setOnClickListener(openMapListener);
	}
	@Override
	public void onBackPressed() {
	   finish();
	   return;
	}
	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		Log.i("DescriptionActivity.onKeyDown",
//				"method started with attribute: " + keyCode);
//		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//			// setContentView(R.layout.main);
//			Intent i = new Intent(this, MainActivity.class);
//			startActivity(i);
//			finish();
//			return true;
//		}
//
//		return super.onKeyDown(keyCode, event);
//	}

	private String loadDescription(String routeDirectoryPath){
		String descPath = routeDirectoryPath+File.separator+TXT_DIR;
		String ret = null;
		File txtDir = new File(descPath);
		if(txtDir.exists() && txtDir.isDirectory()){
			File[] txtFiles = txtDir.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String filename) {
					if(filename.toLowerCase().endsWith(".txt"))
						return true;
					else return false;
				}
			});
			if(txtFiles.length >0){
				try{
					ret = getContents(txtFiles[0]);
				}catch(Exception ex){
					Log.e("DescriptionActivity.loadDescription", "Error during loading a file",ex);
				}
				
			}else{
				Log.e("DescriptionActivity.loadDescription", "No text files found");
			}
		}else{
			Log.e("DescriptionActivity.loadDescription", "Txt dir doesn't exist");
		}
		return ret;
	}
	
	private Bitmap[] loadImages(String routeDirectoryPath){
		Bitmap[] ret = null;
		String imgPath = routeDirectoryPath+File.separator+IMG_DIR;
		File imgDir = new File(imgPath);
		if(imgDir.exists() && imgDir.isDirectory()){
			File[] imgFiles = imgDir.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String filename) {
					if(filename.toLowerCase().endsWith(".jpg"))
						return true;
					else if(filename.toLowerCase().endsWith(".jpeg"))
						return true;
					else return false;
				}
			});
			if(imgFiles.length >0){
				ret = new Bitmap[imgFiles.length];
				for(int i=0; i<imgFiles.length; i++){
					ret[i] = BitmapFactory.decodeFile(imgFiles[i].getAbsolutePath());
				}
			}else{
				Log.e("DescriptionActivity.loadImages", "No image files found");
			}
		}else{
			Log.e("DescriptionActivity.loadImages", "Img dir doesn't exist");
		}
		return ret;
	}
	
	private void openMap() {
		Bundle b = new Bundle();
		String gpxPath = routeDirectoryPath+File.separator+GPX_DIR;
		b.putString("gpx_path",gpxPath);
		Intent i = new Intent(this, MapsActivity.class);
		i.putExtras(b);
		startActivity(i);
	}
	static public String getContents(File aFile) {
	    StringBuilder contents = new StringBuilder();
	    
	    try {
	      BufferedReader input =  new BufferedReader(new FileReader(aFile));
	      try {
	        String line = null; 
	        while (( line = input.readLine()) != null){
	          contents.append(line);
	          contents.append(System.getProperty("line.separator"));
	        }
	      }
	      finally {
	        input.close();
	      }
	    }
	    catch (IOException ex){
	      ex.printStackTrace();
	    }
	    
	    return contents.toString();
	  }
}
